<template>
  <div>
    <myDivider :name="scene == 'add' ? '新增入伙信息' : '修改入伙信息'"></myDivider>
    <el-page-header @back="$router.push('/Admission/AdmissionList')">
    </el-page-header>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" style="width: 600px;margin-top: 20px;" label-width="100px">
      <el-form-item label="房间信息：" prop="roomIdsArray">
        <div style="display: flex;">
          <myCascader v-if="myCascaderShow" :defaultVal="defaultVal" :props="props" @getData="myCascaderGetData">
          </myCascader>
        </div>
      </el-form-item>
      <el-form-item label="客户信息：" prop="customerId">
        <div style="display: flex;">
          <el-input :value="ruleForm.customerName + ' ' + ruleForm.phone" placeholder="请选择客户" disabled
            style="flex:1"></el-input>

          <el-button style="margin-left: 10px;" type="primary" @click="choiceUser">选择</el-button>
        </div>

      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="购房合同号：" prop="contractNumber">
            <el-input style="width: 180px;" placeholder="请输入" maxlength="20"
              v-model="ruleForm.contractNumber"></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="入伙收费：" prop="registerCharge">
            <div style="display: flex;justify-content: space-between;">
              <el-input id="numbera" style="width: 180px;" v-model="ruleForm.registerCharge" placeholder="请输入"
                type="number" oninput="if(value.length>7){value=value.slice(0,7)}"></el-input>
              <span>元</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="钥匙发放：" prop="keyProvide">
        <el-input v-model="ruleForm.keyProvide" maxlength="50" show-word-limit placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="资料发放：" prop="informationProvide">
        <el-input placeholder="请输入" type="textarea" maxlength="100" show-word-limit :row="3"
          v-model="ruleForm.informationProvide"></el-input>
      </el-form-item>
      <el-form-item label="入伙日期：" prop="admissionDate">
        <el-date-picker value-format="yyyy.MM.dd" v-model="ruleForm.admissionDate" type="date" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="图片：">
        <MyUploadImgNotDetele v-if="MyUploadImgNotDeteleShow" :canUploadNum="5" @deleteImgList="deleteImgList"
          @getImgList="getImgList" :id="uploadId" :EchoImgList="EchoImgList" uploadUrl="/business/admission/uploadImg">
        </MyUploadImgNotDetele>
      </el-form-item>

      <el-form-item label="附件：">
        <MyUploadFileNotDetele v-if="MyUploadFileNotDeteleShow" @deleteFileList="deleteFileList"
          @getFileList="getFileList" :id="uploadId" :EchoFileList="EchoFileList"
          uploadUrl="/business/admission/uploadAnnex">
        </MyUploadFileNotDetele>
      </el-form-item>
      <el-form-item label="经办人：" prop="" required>
        <el-input disabled style="width: 200px;" v-model="ruleForm.name" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="归档日期：" v-if="scene == 'update'">
        <el-input disabled style="width: 200px;" v-model="ruleForm.createTime" placeholder=""></el-input>
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="onSubmit('ruleForm')">{{ scene == 'add' ? '新增' : '修改' }}</el-button>
        <el-button type="info" @click="$router.push('/Admission/AdmissionList')">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 客户列表 -->
    <div class="dialogStyle">
      <el-dialog title="客户列表" :visible.sync="dialogShow" width="700px" :close-on-click-modal="false">
        <div style="display: flex;justify-content: space-around;">
          <el-input style="width: 150px;" type="text" v-model="userKeyphone" placeholder="用户手机号"></el-input>
          <el-input style="width: 150px;" type="text" v-model="userKeyname" placeholder="用户姓名"></el-input>
          <el-input style="width: 200px;" type="text" v-model="userKeyIdNumber" placeholder="用户身份证号"></el-input>
          <el-button type="primary" @click="searchForUser">查询</el-button>
        </div>
        <span v-if="popUserData.length == 0"
          style="text-align: center;display: block;width: 100%;margin: 100px 0;">请您输入搜索条件进行查询</span>
        <el-table v-else height="250" :data="popUserData" style="width: 100%;margin-top: 20px;">
          <el-table-column prop="phone" label="手机号" width="150">
          </el-table-column>
          <el-table-column prop="customerName" label="姓名" width="150">
          </el-table-column>
          <el-table-column prop="idNumber" label="身份证号">
          </el-table-column>
          <el-table-column label="确认选择" width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="ChangeUser(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import axios from 'axios'
import myCascader from '@/components/myCascader.vue'
import MyUploadImgNotDetele from '@/components/upload/MyUploadImgNotDetele'
import MyUploadFileNotDetele from '@/components/upload/MyUploadFileNotDetele'
export default {
  components: {
    MyUploadImgNotDetele,
    MyUploadFileNotDetele,
    myCascader
  },
  watch: {

  },
  data() {
    return {
      defaultVal: '',
      myCascaderShow: false,
      props: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad: async (node, resolve) => {
          console.log(node, '级联选择器');
          const { level } = node;
          if (level == 0) {
            let res = await this.$api.events.getCellList(
              {
                name: '',
                pageNum: 1,
                pageSize: 10000,
                roleIds: this.logOnUser.roleIds
              })
            if (res.code == 200) {
              console.log(res.data.list, 'ahhh');
              resolve(res.data.list)

            } else {
              this.$message.error(res.message)
            }
          } else if (level == 1) {
            // 获取楼宇列表
            let res = await this.$api.events.getBuildingList({
              "residentialQuartersId": node.path[0]
            })
            if (res.code == 200) {
              resolve(res.data.list)
            } else {
              this.$message.error(res.message)
            }
          } else if (level == 2) { //获取单元列表
            let res = await this.$api.axios.post('/business/room/getUnitCodeListByBuildingId', {
              "buildingId": node.path[1]
            })
            if (res) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  name: el.name,
                  id: el.value,
                })
              })
              resolve(arr)
            }
          } else if (level == 3) { //获取楼层
            let res = await this.$api.axios.post('/business/room/getFloorsListByBuildingId', {
              "buildingId": node.path[1], //楼宇id  必填
              "unitCode": node.path[2]
            })
            if (res) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  name: el.name,
                  id: el.value,
                })
              })
              resolve(arr)
            }
          } else if (level == 4) {
            let res = await this.$api.axios.post('/business/room/getRoomListByFloors', {
              "buildingId": node.path[1], //楼宇id  必填
              "unitCode": node.path[2],
              "floors": node.path[3] //楼层  必填
            })
            if (res) {
              if (res.data.length > 0) {
                let arr = []
                res.data.forEach(el => {
                  arr.push({ ...el, leaf: true })
                })
                resolve(arr)
              } else {
                resolve([{
                  name: '暂无房间',
                  id: 0,
                  disabled: true,
                  leaf: true
                }])
              }

            }
          } else {
            resolve()
          }

        }
      },
      // 客户弹窗
      dialogShow: false,
      userKeyphone: '',
      userKeyname: '',
      userKeyIdNumber: '',
      popUserData: [],

      userData: {}, //登录用户信息

      keyValue: 0,//级联选择器key的渲染id



      scene: '',
      // 表单相关
      ruleForm: {},
      rules: {
        roomIdsArray: [
          { required: true, message: '请选择房间', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
      },
      //图片相关
      uploadId: 0, //图片和附件的上传
      EchoImgList: [],//要回显的图片
      deleteImg: [],//要删除的图片
      MyUploadImgNotDeteleShow: false,
      //附件
      EchoFileList: [],//要回显的附件
      deleteFile: [],//要删除的附件列表
      MyUploadFileNotDeteleShow: false,
      logOnUser: {}
    }
  },
  async activated() {
    this.logOnUser = sessionStorage.getItem('logOnUser')
    document.getElementById('numbera').addEventListener('input', function (e) {
      if (this.value < 0) {
        this.value = 0
      }
    });
    this.scene = this.$route.query.scene
    this.userData = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.$set(this.ruleForm, 'name', this.userData.name)
    this.MyUploadImgNotDeteleShow = false
    this.MyUploadFileNotDeteleShow = false
    this.userKeyname = ''
    this.userKeyphone = ''
    this.userKeyIdNumber = ''
    this.EchoImgList = [] //要回显的图片清空
    this.deleteImg = []  //把要删除的图片数组清空
    this.EchoFileList = [] //要回显的附件清空
    this.deleteFile = []  //把要删除的附件数组清空
    switch (this.scene) {
      case 'add':
        // 图片附件直接展示
        setTimeout(() => {
          this.MyUploadImgNotDeteleShow = true
          this.MyUploadFileNotDeteleShow = true
        }, 100)
        //级联选择器相关 级联选择器相关
        this.myCascaderShow = false
        this.defaultVal = ''
        setTimeout(() => {
          this.myCascaderShow = true
        }, 50)
        // ================================

        //清空数据
        this.uploadId = 0
        this.$set(this.ruleForm, 'roomIdsArray', [])
        this.$set(this.ruleForm, 'customerId', '')
        this.$set(this.ruleForm, 'contractNumber', '')
        this.$set(this.ruleForm, 'registerCharge', '')
        this.$set(this.ruleForm, 'keyProvide', '')
        this.$set(this.ruleForm, 'informationProvide', '')
        this.$set(this.ruleForm, 'annexPathArray', [])
        this.$set(this.ruleForm, 'imagePaths', [])
        this.$set(this.ruleForm, 'admissionDate', '')
        this.$set(this.ruleForm, 'customerName', '') //客户姓名
        this.$set(this.ruleForm, 'phone', '') //客户手机号
        this.$set(this.ruleForm, 'roomNamesArray', '')//房间文字信息
        // ================================

        break
      case 'update':
        //获取详情
        let res = await this.$api.customer.myAdmissionDetail(this.$route.query.id)
        if (res.code == 200) {
          let data = res.data
          console.log(data, '详情数据');

          //级联选择器相关 级联选择器相关
          this.myCascaderShow = false
          if (res.data.roomNamesArray && res.data.roomNamesArray.length > 0) {
            this.defaultVal = res.data.roomNamesArray.join('/')
          } else {
            this.defaultVal = ''
          }
          this.$set(this.ruleForm, 'roomIdsArray', [data.residentialId, data.buildingId, data.roomId])
          setTimeout(() => {
            this.myCascaderShow = true
          }, 50)
          // ================================

          // 回显客户信息
          this.$set(this.ruleForm, 'customerName', data.customerName) //客户姓名
          this.$set(this.ruleForm, 'phone', data.phone) //客户手机号
          this.$set(this.ruleForm, 'customerId', data.customerId)//客户id
          // ================================

          this.$set(this.ruleForm, 'roomNamesArray', data.roomNamesArray)//房间文字信息

          //基础信息
          this.$set(this.ruleForm, 'contractNumber', data.contractNumber) //购房合同号回显
          this.$set(this.ruleForm, 'registerCharge', data.registerCharge == 0 ? null : data.registerCharge)//入伙收费回显
          this.$set(this.ruleForm, 'keyProvide', data.keyProvide)//钥匙发放回显
          this.$set(this.ruleForm, 'informationProvide', data.informationProvide)//资料发放回显
          this.$set(this.ruleForm, 'admissionDate', data.admissionDate)//入伙日期回显
          this.$set(this.ruleForm, 'createTime', data.createTime)//归档日期回显
          // ================================

          //处理附件  图片
          this.uploadId = data.id
          if (data.imagePaths) {
            this.EchoImgList = data.imagePaths
            this.$set(this.ruleForm, 'imagePaths', data.imagePaths)
          }
          if (data.annexPathArray) {
            this.EchoFileList = data.annexPathArray
            this.$set(this.ruleForm, 'annexPathArray', data.annexPathArray)
          }
          setTimeout(() => {
            this.MyUploadImgNotDeteleShow = true
            this.MyUploadFileNotDeteleShow = true
          }, 100)
          // ================================


        } else {
          this.$message.error(res1.message)
        }



        break
    }
    this.$nextTick(() => {
      this.$refs.ruleForm.clearValidate()
    })
  },
  methods: {
    myCascaderGetData(e) {
      console.log(e, '级联选择器的值')
      // 要替换的
      if (e.ids.length == 0) {
        this.$set(this.ruleForm, 'roomIdsArray', [])
        this.$set(this.ruleForm, 'roomNamesArray', [])
      } else {
        this.$set(this.ruleForm, 'roomIdsArray', [e.ids[0], e.ids[1], e.ids[4]])
        this.$set(this.ruleForm, 'roomNamesArray', [e.names[0], e.names[1], e.names[4]])
      }
      // 替换成的
      // this.$set(this.ruleForm, 'roomIdsArray', e.ids)
      // this.$set(this.ruleForm, 'roomNamesArray', e.names)
    },
    onSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$confirm('请检查信息无误后提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            //删除要删除的图片   
            if (this.deleteImg.length > 0) {
              this.deleteImg.forEach(async el => {
                let res = await this.$api.ImgFile.delete(defaultUrl + '/business/admission/deleteImg', {
                  "imageUrl": el
                })

              })
            }
            //删除要删除的附件  
            if (this.deleteFile.length > 0) {
              this.deleteImg.forEach(async el => {
                let res = await this.$api.ImgFile.delete(defaultUrl + '/business/admission/deleteAnnex', {
                  "filePath": el
                })

              })
            }
            switch (this.scene) {
              case 'add':
                let params = {
                  roomIdsArray: this.ruleForm.roomIdsArray ? this.ruleForm.roomIdsArray : [],
                  roomNamesArray: this.ruleForm.roomNamesArray ? this.ruleForm.roomNamesArray : [],
                  customerId: this.ruleForm.customerId ? this.ruleForm.customerId : '',
                  customerName: this.ruleForm.customerName ? this.ruleForm.customerName : '',
                  phone: this.ruleForm.phone ? this.ruleForm.phone : '',
                  contractNumber: this.ruleForm.contractNumber ? this.ruleForm.contractNumber : '',
                  registerCharge: this.ruleForm.registerCharge ? this.ruleForm.registerCharge : '',
                  keyProvide: this.ruleForm.keyProvide ? this.ruleForm.keyProvide : '',
                  informationProvide: this.ruleForm.informationProvide ? this.ruleForm.informationProvide : '',
                  imagePaths: this.ruleForm.imagePaths ? this.ruleForm.imagePaths : [],
                  annexPathArray: this.ruleForm.annexPathArray ? this.ruleForm.annexPathArray : [],
                  admissionDate: this.ruleForm.admissionDate ? this.ruleForm.admissionDate : '',
                  unitType: this.userData.unitType,
                  unitId: this.userData.unitId,
                }

                let res = await this.$api.customer.myAdmissionInsert(params)
                if (res.code == 200) {
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  });
                  this.$router.push('/Admission/AdmissionList')
                } else {
                  this.$message.error(res.message)
                }
                break
              case 'update':
                let Updateparams = {
                  id: this.$route.query.id,
                  roomIdsArray: this.ruleForm.roomIdsArray ? this.ruleForm.roomIdsArray : [],
                  roomNamesArray: this.ruleForm.roomNamesArray ? this.ruleForm.roomNamesArray : [],
                  customerId: this.ruleForm.customerId ? this.ruleForm.customerId : '',
                  customerName: this.ruleForm.customerName ? this.ruleForm.customerName : '',
                  phone: this.ruleForm.phone ? this.ruleForm.phone : '',
                  contractNumber: this.ruleForm.contractNumber ? this.ruleForm.contractNumber : '',
                  registerCharge: this.ruleForm.registerCharge ? this.ruleForm.registerCharge : '',
                  keyProvide: this.ruleForm.keyProvide ? this.ruleForm.keyProvide : '',
                  informationProvide: this.ruleForm.informationProvide ? this.ruleForm.informationProvide : '',
                  imagePaths: this.ruleForm.imagePaths ? this.ruleForm.imagePaths : [],
                  annexPathArray: this.ruleForm.annexPathArray ? this.ruleForm.annexPathArray : [],
                  admissionDate: this.ruleForm.admissionDate ? this.ruleForm.admissionDate : '',
                }
                let Updateres = await this.$api.customer.myAdmissionUpdate(Updateparams)
                if (Updateres.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.$router.push('/Admission/AdmissionList')
                } else {
                  this.$message.error(Updateres.message)
                }

                break
            }

          }).catch(() => {

          });
        }
      });
    },
    choiceUser() {

      this.dialogShow = true
      this.userKeyphone = ''
      this.userKeyname = ''
      this.userKeyIdNumber = ''
      this.popUserData = []
    },
    async searchForUser() { //用户列表条件查询搜索事件

      if (this.userKeyphone == '' && this.userKeyname == '' && this.userKeyIdNumber == '') {
        this.$message.error('数据量太多，请输入搜索条件进行筛选')
        this.popUserData = []
        return
      }
      let res = await this.$api.customer.myGetCustomerList({
        "name": this.userKeyname, //客户姓名
        "phoneNumber": this.userKeyphone, //客户手机号
        "idNumber": this.userKeyIdNumber, //客户身份证号
        "pageSize": 100000,
        "pageNum": 1
      })
      console.log(res, '用户列表');
      if (res.code == 200) {
        this.popUserData = res.data.list
      } else {
        this.$message.error(res.message)
      }

    },
    ChangeUser(val) { //点击了用户列表弹窗的选择按钮
      this.$set(this.ruleForm, 'customerName', val.customerName)
      this.$set(this.ruleForm, 'phone', val.phone)
      this.$set(this.ruleForm, 'customerId', val.customerId)
      this.dialogShow = false
    },




    deleteImgList(val) { //删除图片的事件，点击保存再删除
      this.deleteImg.push(val)
    },
    deleteFileList(val) {//删除附件的事件，点击保存再删除
      this.deleteFile.push(val)
    },
    getImgList(val) { //图片列表
      this.ruleForm.imagePaths = val
    },
    getFileList(val) { //附件列表
      this.ruleForm.annexPathArray = val
    },
  },
}
</script>

<style lang="less" scoped>
.btn {
  position: fixed;
  bottom: 10px;
  right: 70px;
}
</style>